package com.holy.sh.couviewholy.myview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.Region;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.holy.sh.couviewholy.R;

/**
 * Holy Email :victorhhl@163.com
 * Create by Holy on ${data}
 * Description :
 */
public class VisibleView extends SurfaceView implements SurfaceHolder.Callback, Runnable{


    //用于控制SurfaceView
    private SurfaceHolder sfh;
    //声明一个画笔
    private Paint paint;
    //声明一条线程
    private Thread th;
    //线程消亡的标识位
    private boolean flag;
    //声明一个画布
    private Canvas canvas;
    //声明屏幕的宽高
    private int screenW, screenH;
    private Bitmap bmp;
    private int x=30,y=30;
    int pw ;
    int ph ;
    private Context mContext;
    private int bmp_id;
    private int cavensColor;
    private int radius_size;


    /**
     * SurfaceView初始化函数
     */
    public VisibleView(Context context) {
        super(context);
        //实例SurfaceHolder
        initOP();
        mContext=context;
    }


    public VisibleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initAttrs(attrs);
        initOP();
        mContext=context;
    }

    private void initAttrs(AttributeSet attrs) {
         TypedArray a=getContext().obtainStyledAttributes(attrs,R.styleable.VisibleView);
          bmp_id=a.getResourceId(R.styleable.VisibleView_bg_pic,-1);
          cavensColor=a.getColor(R.styleable.VisibleView_mp_color,-1);
          radius_size=a.getInt(R.styleable.VisibleView_radius_size,60);
    }

    public VisibleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttrs(attrs);
        initOP();
        mContext=context;
    }


    private void  initOP(){
        sfh = this.getHolder();
        //为SurfaceView添加状态监听
        sfh.addCallback(this);
        //实例一个画笔
        paint = new Paint();
        //设置画笔颜色为白色
        paint.setColor(Color.WHITE);
        //设置画笔无锯齿
        paint.setAntiAlias(true);
        //设置焦点
        setFocusable(true);
        bmp = BitmapFactory.decodeResource(this.getResources(), bmp_id);
        DisplayMetrics ds = new DisplayMetrics();

        //getWindowManager().getDefaultDisplay().getMetrics(ds);
          pw = ds.widthPixels;
          ph = ds.heightPixels;
       /* Log.i("ppp","pw"+pw);
        Log.i("ppp","py"+ph);*/

    }

    /**
     * SurfaceView视图创建，响应此函数
     */
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        screenW = this.getWidth();
        screenH = this.getHeight();
        Log.i("screenW",""+screenW);
        Log.i("screenH",""+screenH);
        flag = true;
        //实例线程
        th = new Thread(this);
        //启动线程
        th.start();
    }

    /**
     * 游戏绘图
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public void myDraw() {
        try {
            canvas = sfh.lockCanvas();
            if (canvas != null) {
                canvas.drawColor(cavensColor);
                //----设置矩形可视区域
                /*canvas.save();
                canvas.clipRect(0, 0, 20, 20);
                canvas.drawBitmap(bmp, 0, 0, paint);
                canvas.restore();*/
                //----利用Path设置可视区域
                canvas.save();
                Path path = new Path();
                path.addCircle(x, y, radius_size, Path.Direction.CCW);
                canvas.clipPath(path);
                Rect bitR=new Rect(0,0,screenW,screenH);
                canvas.drawBitmap(bmp, null, bitR, paint);
                canvas.restore();
                //----利用Region设置可视区域
               /* canvas.save();
                Region region = new Region();
                region.op(new Rect(20,20,100,100), Region.Op.UNION);
                region.op(new Rect(40,20,80,150), Region.Op.XOR);
               // canvas.clipRegion(region);
                canvas.clipRect(new Rect(40,20,80,150));
                canvas.drawBitmap(bmp, 0, 0, paint);
                canvas.restore();*/
            }
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            if (canvas != null)
                sfh.unlockCanvasAndPost(canvas);
        }
    }

    /**
     * 触屏事件监听
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int px= (int) event.getX();
        int py= (int) event.getY();
        x=px-100;
        y=py-100;
        myDraw();
        return true;
    }

    /**
     * 按键事件监听
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 游戏逻辑
     */
    private void logic() {

    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void run() {
        while (flag) {
            long start = System.currentTimeMillis();
            myDraw();
            logic();
            long end = System.currentTimeMillis();
            try {
                if (end - start < 50) {
                    Thread.sleep(50 - (end - start));
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * SurfaceView视图状态发生改变，响应此函数
     */
    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {


    }

    /**
     * SurfaceView视图消亡时，响应此函数
     */
    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        flag = false;
    }

}
